package com.haoze.nurseapp.controller;

import com.haoze.common.utils.IOConvertUtil;
import com.haoze.common.utils.JSONUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.Map;

@RestController
@RequestMapping("/nurseapp/file")
@Api("app上传")
public class FileController {

    @Value("${app.remoteUpUrl}")
    private String remoteUpUrl;

    /**
     * 上传文件
     *
     * @param folder
     * @param uploadImg
     * @return
     * @throws IOException
     * @throws URISyntaxException
     */
    @PostMapping(value = "uploadfile",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Map uploadFile(@RequestParam("folder") String folder, @RequestParam("file") MultipartFile uploadImg) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", new FileSystemResource(IOConvertUtil.multipartFileToFile(uploadImg)));
        body.add("folder", folder);
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body, headers);
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectionRequestTimeout(3000);
        factory.setConnectTimeout(5000);
        RestTemplate restTemplate = new RestTemplate(factory);
        ResponseEntity<String> response = restTemplate.exchange(remoteUpUrl, HttpMethod.POST, entity, String.class);
        return JSONUtils.jsonToMap(response.getBody());
    }

}
